import { useNavigate } from 'react-router-dom'
import { useState } from 'react'
import { Upload, Button, Form, Input, Select, message, Card } from 'antd'
import { UploadOutlined } from '@ant-design/icons'
import axios from 'axios'
import { getAuthToken } from '@/router'

export default function TorrentUpload() {
  const [form] = Form.useForm()
  const [fileList, setFileList] = useState([])
  const [loading, setLoading] = useState(false)
  const navigate = useNavigate()

  const handleUpload = async (values) => {
    if (fileList.length === 0) {
      message.error('请选择种子文件')
      return
    }

    const formData = new FormData()
    formData.append('file', fileList[0])
    formData.append('name', values.name)
    formData.append('category', values.category)
    formData.append('description', values.description)

    try {
      setLoading(true)
      const res = await axios.post('/api/v1/torrent/upload', formData, {
        headers: {
          Authorization: `Bearer ${getAuthToken()}`,
          'Content-Type': 'multipart/form-data'
        }
      })
      message.success(`上传成功，种子ID: ${res.data.data.torrentId}`)
      form.resetFields()
      setFileList([])
      navigate('/') // 上传成功后自动返回首页
    } catch (error) {
      message.error(error.response?.data?.message || '上传失败')
    } finally {
      setLoading(false)
    }
  }

  return (
    <Card 
      title="上传种子"
      className="upload-card"
      extra={
        <Button 
          type="link" 
          onClick={() => navigate(-1)}
          style={{ padding: 0 }}
        >
          返回首页
        </Button>
      }
    >
      <Form form={form} onFinish={handleUpload}>
        <Form.Item name="name" label="资源名称" rules={[{ required: true }]}>
          <Input />
        </Form.Item>
        
        <Form.Item name="category" label="分类" rules={[{ required: true }]}>
          <Select options={[
            { value: 'movie', label: '电影' },
            { value: 'tv', label: '剧集' },
            { value: 'music', label: '音乐' }
          ]}/>
        </Form.Item>

        <Form.Item name="description" label="描述">
          <Input.TextArea />
        </Form.Item>

        <Form.Item label="种子文件" required>
          <Upload
            fileList={fileList}
            beforeUpload={(file) => {
              setFileList([file])
              return false
            }}
            onRemove={() => setFileList([])}
          >
            <Button icon={<UploadOutlined />}>选择文件</Button>
          </Upload>
        </Form.Item>

        <Button 
          type="primary" 
          htmlType="submit"
          loading={loading}
          style={{ width: 150, height: 40 }}
        >
          提交上传
        </Button>
      </Form>
    </Card>
  )
}